<?php

namespace app\api\controller;

use app\common\model\ViperActivityProject;
use think\Db;
use app\common\model\ViperType as ViperTypeModel;
use think\Exception;
use app\common\model\RechargeTemplate;
use app\common\model\NumberCardTemplate;
use app\common\model\MonthCardTemplate;
use app\common\model\MonthCardItem;
use app\common\model\ViperActivityGoods;

/**
 * 会员卡类型控制器
 * @package app\index\controller
 */
class ViperType extends Auth
{
    public $noNeedLogin = '';

    /**
     * 基础数据--设置会员类型---添加会员类型
     * name  expire_month  is_across_store_recharge  is_across_store_give
     * is_discount rule  amount integral_1  integral_2
     * recharge  [{ name:'',amount:'',give_amount:'',rate:'',integral:'',type:'',moth:''}]
     * number    [{'name':'','amount':'',rate:'',item:[{id:'',number:'',expire:'',type:'goods'}]}]
     * month    [{name:'',amount:'',rate:'',hz:'',expire:'',type:'',item:[{id:'',type:''}]}]
     * goods
     * [{id:'',type:'',value:'',start:'',end:'',viper_price:'',range_vip_price:'',rule:''}]
     * projects
     * [{id:'',type:'',value:'',start:'',end:'',viper_price:'',add_block_price:'',range_vip_price:'',range_add_block_price:'',rule:''}]
     *
     * viper_price:会员价,add_block_price,加钟价,range_viper_price,时段会员价,range_add_block_price,时段加钟价
     *
     *[{'name':'','amount':'',rate:'',item:[{data:[{'id':'',type:'goods'}],number:'',expire:''}]}]
     *
     * [{name:'',amount:'',rate:'',hz:'',expire:'',type:'',item:[[{data:[{'id':'',type:'goods'}]]}]
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $validate = new \app\api\validate\ViperType();

            if (!$validate->check($data)) {
                $this->result($validate->getError(), '', 204);
            }
            if (!isset($data['integral_2'])) {
                $data['integral_2'] = '';
            }
            if (!isset($data['integral_1'])) {
                $data['integral_1'] = '';
            }
            if (!isset($data['use_number_warning'])) {
                $data['use_number_warning'] = '';
            }
            $arr = [
                'name' => $data['name'],
                'expire_month' => $data['expire_month'],
                'silence' => !empty($data['silence']) ? $data['silence'] : 0,
                'rule' => $data['rule'],
                'amount' => $data['amount'],
                'integral_1' => $data['integral_1'],
                'integral_2' => $data['integral_2'],
                'use_number_warning' => $data['use_number_warning'],
                'is_across_store_recharge' => $data['is_across_store_recharge'],
                'is_across_store_give' => $data['is_across_store_give'],
                'is_discount' => $data['is_discount'],
            ];
            //Db::startTrans();

            //try {

                $arr['store_id'] = $this->userInfo['store_id'];
                $type = ViperTypeModel::create($arr);
                if (key_exists('recharge', $data) && !empty($data['recharge']) && strlen($data['recharge']) > 0) {
                    $recharge_template = json_decode($data['recharge'], true);
                    RechargeTemplate::createByTemplates($recharge_template, $this->userInfo['store_id'], $type['id'], $this->userInfo['id']);
                }

                if (key_exists('number', $data) && !empty($data['number']) && strlen($data['number']) > 0) {
                    $number_template = json_decode($data['number'], true);
                    NumberCardTemplate::createByTemplate($number_template, $this->userInfo['store_id'], $type['id']);
                }

                if (key_exists('month', $data) && !empty($data['month']) && strlen($data['month']) > 0) {
                    $month_template = json_decode($data['month'], true);
                    MonthCardTemplate::createByTemplate($month_template, $this->userInfo['store_id'], $type['id']);
                }

                if (key_exists('goods', $data) && !empty($data['goods']) && strlen($data['goods']) > 0) {
                    $goods = json_decode($data['goods'], true);
                    ViperActivityGoods::createByTemplate($goods, $this->userInfo['store_id'], $type['id']);
                }

                if (key_exists('projects', $data) && !empty($data['projects']) && strlen($data['projects']) > 0) {
                    $projects = json_decode($data['projects'], true);
                    ViperActivityProject::createByTemplate($projects, $this->userInfo['store_id'], $type['id']);
                }

//                Db::commit();
//            } catch (Exception $e) {
//                Db::rollback();
//                halt($e->getMessage());
//            }
            $this->result('操作成功', '', 200);

        } else {
            $this->result('操作错误', '', 204);
        }


    }

    /**
     * 基础数据--设置会员类型---添加或者编辑会员类型
     * name  expire_month  is_across_store_recharge  is_across_store_give
     * is_discount rule  amount integral_1  integral_2
     * viper_type_id
     * recharge[{name:'',amount:'',rate:'',integral:'',month:'',type:''}]
     * number[{'name':'','amount':'',rate:'',item:[{id:'',number:'',expire:'',type:'goods'}]}]
     * month [{name:'',amount:'',rate:'',hz:'',expire:'',type:'',item:[{id:'',type:''}]}]
     * goods
     * [{id:'',type:'',value:'',start:'',end:'',viper_price:'',range_vip_price:''}]
     * projects
     * [{id:'',type:'',value:'',start:'',end:'',viper_price:'',add_block_price:'',range_vip_price:'',range_add_block_price:''}]
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $validate = new \app\api\validate\ViperType();

            if (!$validate->check($data)) {
                $this->result($validate->getError(), '', 204);
            }
            if (!isset($data['integral_2'])) {
                $data['integral_2'] = '';
            }
            if (!isset($data['integral_1'])) {
                $data['integral_1'] = '';
            }
            if (!isset($data['use_number_warning'])) {
                $data['use_number_warning'] = '';
            }
            if (!isset($data['use_number_warning'])) {
                $data['use_number_warning'] = '';
            }
            $arr = [
                'name' => $data['name'],
                'expire_month' => $data['expire_month'],
                'rule' => $data['rule'],
                'amount' => $data['amount'],
                'integral_1' => $data['rule'],
                'integral_2' => $data['integral_2'],
                'use_number_warning' => $data['use_number_warning'],
                'is_across_store_recharge' => $data['is_across_store_recharge'],
                'is_across_store_give' => $data['is_across_store_give'],
                'is_discount' => $data['is_discount'],
            ];

            if (!$data['viper_type_id']) {
                $this->result('缺少必要参数', '', 204);
            }

            Db::startTrans();
            try {
                ViperTypeModel::where('id', $data['viper_type_id'])->update($arr);
                if (key_exists('recharge', $data) && !empty($data['recharge']) && strlen($data['recharge']) > 0) {
                    RechargeTemplate::where(['store_id' => $this->userInfo['store_id'], 'viper_type_id' => $data['viper_type_id']])->delete();
                    $recharge_template = json_decode($data['recharge'], true);
                    RechargeTemplate::createByTemplates($recharge_template, $this->userInfo['store_id'], $data['viper_type_id'], $this->userInfo['id']);
                }

                if (key_exists('number', $data) && !empty($data['number']) && strlen($data['number']) > 0) {
                    $number_template = json_decode($data['number'], true);
                    $number_template_card = Db::name('qt_viper_number_card_template')->where('viper_type_id', $data['viper_type_id'])->find();
                    DB::name('qt_viper_number_card_template')->where('viper_type_id', $data['viper_type_id'])->delete();
                    if (!empty($number_template_card)) {
                        DB::name('qt_viper_number_card_template_collection')->where('number_template_id', $number_template_card['id'])->delete();
                        DB::name('qt_viper_number_card_template_item')->where(['number_card_template_id' => $number_template_card['id']])->delete();
                    }
                    NumberCardTemplate::createByTemplate($number_template, $this->userInfo['store_id'], $data['viper_type_id']);

                }


                if (key_exists('number', $data) && !empty($data['month']) && strlen($data['month']) > 0) {
                    $month_template = json_decode($data['month'], true);
                    MonthCardTemplate::where(['store_id' => $this->userInfo['store_id'], 'viper_type_id' => $data['viper_type_id']])->delete();
                    $number_template_card = Db::name('qt_viper_month_card_template')->where('viper_type_id', $data['viper_type_id'])->find();
                    MonthCardItem::where(['month_template_id' => $number_template_card['id']])->delete();
                    MonthCardTemplate::createByTemplate($month_template, $this->userInfo['store_id'], $data['viper_type_id']);
                }

                if (key_exists('goods', $data) && !empty($data['goods']) && strlen($data['goods']) > 0) {
                    $goods = json_decode($data['goods'], true);
                    DB::name('qt_viper_activity_goods')->where(['store_id' => $this->userInfo['store_id'], 'viper_type_id' => $data['viper_type_id']])->delete();
                    ViperActivityGoods::createByTemplate($goods, $this->userInfo['store_id'], $data['viper_type_id']);
                }

                if (key_exists('projects', $data) && !empty($data['projects']) && strlen($data['projects']) > 0) {
                    $projects = json_decode($data['projects'], true);
                    DB::name('qt_viper_activity_project')->where(['store_id' => $this->userInfo['store_id'], 'viper_type_id' => $data['viper_type_id']])->delete();
                    ViperActivityProject::createByTemplate($projects, $this->userInfo['store_id'], $data['viper_type_id']);
                }
                Db::commit();
                $this->result('操作成功', '', 200);
            } catch (Exception $e) {
                Db::rollback();
                $this->result('请求错误'.$e->getMessage().' 文件：'.$e->getFile().' 行：'.$e->getLine(), '', 204);
            }
        } else {
            $this->result('请求错误', '', 204);
        }
    }

    /**
     * 基本数据--会员类型管理--会员类型详情
     * viper_type_id
     *
     */
    public function detail()
    {
        if ($this->request->isPost()) {
            $viper_type_id = $this->request->post('viper_type_id');

            if (empty($viper_type_id))
                $this->result('缺少必要参数', '', 204);

            $info = ViperTypeModel::where(['store_id' => $this->userInfo['store_id'], 'id' => $viper_type_id])
                ->field('id,name,expire_month,
                silence,rule,amount,integral_1,integral_2,is_across_store_recharge,is_across_store_give,
                is_discount,use_number_warning,birthday_how_long')
                ->find();
            $info['recharge'] = RechargeTemplate::getTemplateOfStore($this->userInfo['store_id'], $viper_type_id);
            $info['number'] = NumberCardTemplate::getTemplateOfStore($this->userInfo['store_id'], $viper_type_id);
            $info['month'] = MonthCardTemplate::getTemplateOfStore($this->userInfo['store_id'], $viper_type_id);
            $info['goods'] = ViperActivityGoods::getActivityGoodsOfStore($this->userInfo['store_id'], $viper_type_id);
            $info['projects'] = ViperActivityProject::getActivityProjectOfStore($this->userInfo['store_id'], $viper_type_id);

            $this->result('获取成功', $info, 200);

        } else {
            $this->result('请求错误', '', 204);
        }
    }

    /**
     * 基本数据--会员类型管理--会员类型列表
     */
    public function lists()
    {
        if ($this->request->isPost()) {
            $list = Db::name('qt_viper_type')->where(['store_id' => $this->userInfo['store_id']])->field('id,name,amount_percentage,give_amount_percentage')->select();
            $this->result('获取成功', $list, 200);
        } else {
            $this->result('请求错误', '', 204);
        }
    }

    /**
     * 基本数据--会员类型--删除会员类型
     */
    public function remove()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if (empty($data['viper_type_id']))
                $this->result('缺少必要参数', '', 204);
            $find = Db::name('qt_viper_card')->where('viper_type_id', $data['viper_type_id'])->find();
            if (!empty($find)) {
                $this->result('该会员卡下面有会员，暂时不支持删除', '', 204);
            }
            $result = ViperTypeModel::destroy($data['viper_type_id']);

            $result ? $this->result('删除成功', '', 200) : $this->result('删除失败', '', 204);
        } else {
            $this->result('请求错误', '', 204);
        }
    }


    /**
     * 设置支付比例
     */
    public function percentage()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['amount_percentage']) || empty($getData['give_amount_percentage']) || empty($getData['viper_type_id'])) {
                $this->result('缺少参数', '', 204);
            }
            if (($getData['amount_percentage'] + $getData['give_amount_percentage']) != 100) {
                $this->result('支付比例相加必须等于100', '', 204);
            }
            $update = Db::name('qt_viper_type')->where(['id' => $getData['viper_type_id']])->update([
                'amount_percentage' => $getData['amount_percentage'],
                'give_amount_percentage' => $getData['give_amount_percentage']
            ]);
            if ($update !== false) {
                $this->result('设置成功', '', 200);
            }
            $this->result('设置失败', '', 204);
        } else {
            $this->result('请求错误', '', 204);
        }
    }


}
